package top.blacknota.dao;

import act.Act;
import cn.hutool.db.DbUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import org.nutz.conf.NutConf;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.impl.NutDao;
import top.blacknota.pojo.User;
import top.blacknota.utils.LpKey;

import java.util.Date;
import java.util.List;

/**
 * Created by 撒哈拉来的企鹅 on 2018-2-8.
 */
public class NDao {
    public static Dao dao = new NutDao(DbUtil.getDs("zc"));
    private Log logger = LogFactory.get();

    public void deleteUser(String userId) {
        dao.delete(User.class, userId);
    }

    public User findUserById(String userId) {
        return dao.fetch(User.class, userId);
    }

    private static class SingletonHolder {
        /**
         * 静态初始化器，由JVM来保证线程安全
         */
        private static NDao instance = new NDao();
    }

    public NDao() {
        NutConf.USE_FASTCLASS = false;
    }

    public static NDao getInstance() {
        return SingletonHolder.instance;
    }

    public static void main(String[] args) {
        boolean exists = dao.exists(User.class);
        System.out.println(exists);
        User user = new User();
        user.setUsername("admin");
        user.setPassword("123");
        user.setCreateTime(new Date());
        dao.insert(user);
    }

    public User findUserByName(String username) {
        return dao.fetch(User.class, Cnd.where("username", "=", username));
    }

    public void addUser(User user) {
        dao.insert(user);
    }

    //
    public LpKey getLpKey(String flag) {
        try {
            return dao.fetch(LpKey.class, Cnd.where("keyName", "=", flag));
        } catch (Exception e) {
            return null;
        }
    }

    public void updateLpKey(String flag, int i) {
        if (i == 0) {
            dao.update(LpKey.class, Chain.makeSpecial("value", "+1").add("time", "now()"), Cnd.where("keyName", "=", flag));
        } else {
            dao.update(LpKey.class, Chain.make("value", 0).add("time", new Date()), Cnd.where("keyName", "=", flag));
        }
    }

    public void initLpKey(String flag) {

        //如果序列表不存在，创建一个
        if (!dao.exists(LpKey.class)) {
            dao.create(LpKey.class, false);
        }

        LpKey lpKey = new LpKey();
        lpKey.setKeyName(flag);
        lpKey.setValue(0);
        lpKey.setTime(new Date());
        dao.insert(lpKey);
    }

    //查找用户
    public User getUser(String username) {
        return dao.fetch(User.class, Cnd.where("username", "=", username));
    }

    //查询全部用户
    public List<User> getAllUser() {
        return dao.query(User.class, Cnd.NEW());
    }

    public void editUserExPwd(User user) {
        dao.update(User.class, Chain.make("username", user.getUsername()), Cnd.where("id", "=", user.getId()));
    }

    public void editUser(User user) {
        dao.update(user);
    }

}
